#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Win7兼容性构建脚本
使用较低版本的依赖来确保在Win7系统上的兼容性
"""

import os
import sys
import subprocess

def check_python_version():
    """检查Python版本是否适合Win7"""
    version = sys.version_info
    print(f"当前Python版本: {version.major}.{version.minor}.{version.micro}")
    
    # 推荐Python 3.7-3.8用于Win7兼容性
    if version.major == 3 and 7 <= version.minor <= 8:
        print("✓ Python版本适合Win7兼容性")
        return True
    else:
        print("⚠ 警告: 建议使用Python 3.7或3.8以获得更好的Win7兼容性")
        return False

def install_dependencies():
    """安装Win7兼容的依赖"""
    print("正在安装Win7兼容的依赖...")
    
    # 卸载现有的PyQt5
    # try:
    #     subprocess.run([sys.executable, "-m", "pip", "uninstall", "PyQt5", "-y"], check=False)
    #     subprocess.run([sys.executable, "-m", "pip", "uninstall", "sip", "-y"], check=False)
    # except:
    #     pass
    
    # 安装Win7兼容版本 - 使用预编译包避免编译问题
    dependencies = [
        "PyQt5_sip==4.19.19",
        "PyQt5==5.12.3",
        "psutil==5.6.7",
        "pyinstaller==4.10"  # 使用较老版本的PyInstaller
    ]
    
    for dep in dependencies:
        print(f"安装 {dep}...")
        result = subprocess.run([sys.executable, "-m", "pip", "install", "--only-binary=all", dep], 
                              capture_output=True, text=True)
        if result.returncode != 0:
            print(f"❌ 安装 {dep} 失败: {result.stderr}")
            return False
        else:
            print(f"✓ 成功安装 {dep}")
    
    return True

def build_for_win7():
    """使用Win7兼容配置构建应用"""
    print("开始构建Win7兼容版本...")
    
    # 设置环境变量以提高兼容性
    env = os.environ.copy()
    env['PYINSTALLER_COMPILE_BOOTLOADER'] = '1'
    
    # 构建命令
    cmd = [
        sys.executable, "-m", "PyInstaller",
        "--clean",
        "--onefile",
        "--windowed",
        "--name", "NetAssist_Win7",
        "--distpath", "dist_win7",
        "--workpath", "build_win7",
        "--specpath", ".",
        "NetAssist_Win7.spec"
    ]
    
    print(f"执行命令: {' '.join(cmd)}")
    result = subprocess.run(cmd, env=env, cwd=os.getcwd())
    
    if result.returncode == 0:
        print("✓ 构建成功!")
        print("Win7兼容版本位于: dist_win7/NetAssist_Win7.exe")
        return True
    else:
        print("❌ 构建失败")
        return False

def main():
    print("=== NetAssist Win7兼容性构建工具 ===")
    print()
    
    # 检查Python版本
    check_python_version()
    print()
    
    # 询问是否继续
    # response = input("是否继续安装Win7兼容依赖并构建? (y/n): ")
    # if response.lower() not in ['y', 'yes', '是', '']:
    #     print("构建已取消")
    #     return
    
    # 安装依赖
    if not install_dependencies():
        print("依赖安装失败，构建终止")
        return
    
    print()
    
    # 构建应用
    if build_for_win7():
        print()
        print("=== 构建完成 ===")
        print("请在Win7系统上测试 dist_win7/NetAssist_Win7.exe")
        print()
        print("如果仍有问题，建议:")
        print("1. 使用Python 3.7.9 (最后支持Win7的版本)")
        print("2. 在Win7系统上直接构建")
        print("3. 使用虚拟机进行测试")
    else:
        print("构建失败，请检查错误信息")

if __name__ == "__main__":
    main()